package com.example.dynamicschedule.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.example.dynamicschedule.base.Constant;
import com.example.dynamicschedule.base.CreditResultDTO;
import com.example.dynamicschedule.bean.*;
import com.example.dynamicschedule.config.ScanningCleaningConfig;
import com.example.dynamicschedule.dao.*;
import com.example.dynamicschedule.redis.RedisService;
import com.example.dynamicschedule.service.CkCreditOutCompanyDataService;
import com.example.dynamicschedule.service.IamGroupService;
import com.example.dynamicschedule.utils.BaseInformationUtils;
import com.example.dynamicschedule.utils.DateUtils;
import com.example.dynamicschedule.utils.HttpClientUtils;
import com.example.dynamicschedule.utils.JSONUtils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class CreditScanningCleaningDataTask {
    @Autowired
    private CkCreditCardLoadNewTonglianMapper ckCreditCardLoadNewTonglianMapper;
    @Autowired
    private CkCreditCardLoadOldTonglianMapper ckCreditCardLoadOldTonglianMapper;
    @Autowired
    private CkCreditCardLoadNewYinshuMapper ckCreditCardLoadNewYinshuMapper;
    @Autowired
    private CkCreditCardLoadOldYinshuMapper ckCreditCardLoadOldYinshuMapper;
    @Autowired
    private CkCreditAccountInfoMapper ckCreditAccountInfoMapper;
    @Autowired
    private CkCreditPeopleInfomationMapper ckCreditPeopleInfomationMapper;
    @Autowired
    private CkCreditLogMapper ckCreditLogMapper;
    @Autowired
    private CkCreditRecoverMoneyMapper ckCreditRecoverMoneyMapper;
    @Autowired
    private CkCreditStopNoticePersonMapper ckCreditStopNoticePersonMapper;
    @Autowired
    private CkCreditCardLoadHistoryMapper ckCreditCardLoadHistoryMapper;
    @Autowired
    private ScanningCleaningConfig scanningCleaningConfig;
    @Autowired
    private DateUtils dateUtils;
    @Autowired
    private CkCreditOutCompanyDataService ckCreditOutCompanyDataService;
    @Autowired
    private CreditUploadFileTask creditUploadFileTask;
    @Autowired
    private RedisService redisService;
    @Autowired
    private BaseInformationUtils baseInformationUtils;

    @Autowired
    private IamGroupService iamGroupService;
    @Autowired
    private CkCreditOutCompanyDataLogMapper ckCreditOutCompanyDataLogMapper;
    @Autowired
    private CreditOutcompanyCommissionTask creditOutcompanyCommissionTask;
    @Autowired
    private CkCreditOutCompanyDataMapper ckCreditOutCompanyDataMapper;
    static Logger log = Logger.getLogger(CreditScanningCleaningDataTask.class);

    /**
     * 信贷清洗规则
     *
     * @throws Exception
     */
    @Transactional
    public void CreditScanningCleaningDataTask() throws Exception {
        log.info("信贷清洗规则---------------------------任务开始");
        //获取大数据通联新表所有数据
        List<CkCreditCardLoadNewTonglian> ckCreditCardLoadNewTonglians = ckCreditCardLoadNewTonglianMapper.selectList();
        //获取大数据通联新旧表所有数据
        List<CkCreditCardLoadOldTonglian> ckCreditCardLoadOldTonglians = ckCreditCardLoadOldTonglianMapper.selectList();
        //获取大数据银数新表所有数据
        List<CkCreditCardLoadNewYinshu> ckCreditCardLoadNewYinShus = ckCreditCardLoadNewYinshuMapper.selectList();
        //获取大数据银数旧表所有数据
        List<CkCreditCardLoadOldYinshu> ckCreditCardLoadOldYinShus = ckCreditCardLoadOldYinshuMapper.selectList();
        //获取失联或者停催数据
        List<CkCreditStopNoticePerson> ckCreditStopNoticePeoples = new ArrayList<>();
        //存储信贷map
        Map<String, List<CreditResultDTO>> creditResultDTOMap = new HashMap<>();
        //模糊查询 yyyyMM
        String likeBatchNumber = dateUtils.getLikeBatchNumber();
        //获取当前批次号
        String batchNumber = dateUtils.getBatchNumber();
        //获取支行和分行的code
        Map<String, String> codeMap = iamGroupService.selectByCode();
        log.info("信贷清洗规则---------------------------通联数据------------------处理开始");
        if (ckCreditCardLoadNewTonglians.size() > 0 || ckCreditCardLoadOldTonglians.size() > 0) {
            //获取当前批次号人员身份证号集合(通联)
            Map<String, Object> params = new HashMap<>();
            params.put("batchNumber", batchNumber);
            params.put("allowType", 1);
            List<String> tongLianPeopleIds = ckCreditPeopleInfomationMapper.selectByLikeBatchNumberAndAllowType(params);
            List<String> cardNumbers = ckCreditAccountInfoMapper.selectByLikeBatchNumberAndAllowType(params);
            List<CkCreditStopNoticePerson> ckCreditStopNoticePeople = ckCreditStopNoticePersonMapper.selectByStatus(1);
            if (CollectionUtils.isNotEmpty(ckCreditStopNoticePeople)) {
                ckCreditStopNoticePeoples.addAll(ckCreditStopNoticePeople);
            }
            ckCreditStopNoticePeople = ckCreditStopNoticePersonMapper.selectByStatus(2);
            if (CollectionUtils.isNotEmpty(ckCreditStopNoticePeople)) {
                ckCreditStopNoticePeoples.addAll(ckCreditStopNoticePeople);
            }
            creditResultDTOMap = tongLianClean(ckCreditCardLoadNewTonglians,
                    ckCreditCardLoadOldTonglians, ckCreditStopNoticePeoples, tongLianPeopleIds,
                    creditResultDTOMap, cardNumbers, codeMap);
        } else {
            log.info("信贷清洗规则---------------------------通联数据------------------数据为空");
        }
        log.info("信贷清洗规则---------------------------通联数据------------------处理结束");
        log.info("信贷清洗规则---------------------------银数数据------------------处理开始");
        if (ckCreditCardLoadNewYinShus.size() > 0 || ckCreditCardLoadOldYinShus.size() > 0) {
            Map<String, Object> params = new HashMap<>();
            params.put("batchNumber", batchNumber);
            params.put("allowType", 2);
            List<String> yinShuPeopleIds = ckCreditPeopleInfomationMapper.selectByLikeBatchNumberAndAllowType(params);
            List<String> cardNumbers = ckCreditAccountInfoMapper.selectByLikeBatchNumberAndAllowType(params);
            ckCreditStopNoticePeoples = new ArrayList<>();
            List<CkCreditStopNoticePerson> ckCreditStopNoticePeople = ckCreditStopNoticePersonMapper.selectByStatus(1);
            if (CollectionUtils.isNotEmpty(ckCreditStopNoticePeople)) {
                ckCreditStopNoticePeoples.addAll(ckCreditStopNoticePeople);
            }
            ckCreditStopNoticePeople = ckCreditStopNoticePersonMapper.selectByStatus(2);
            if (CollectionUtils.isNotEmpty(ckCreditStopNoticePeople)) {
                ckCreditStopNoticePeoples.addAll(ckCreditStopNoticePeople);
            }
            creditResultDTOMap = yinShuClean(ckCreditCardLoadNewYinShus, ckCreditCardLoadOldYinShus,
                    ckCreditStopNoticePeoples, yinShuPeopleIds, creditResultDTOMap, cardNumbers, codeMap);

        } else {
            log.info("信贷清洗规则---------------------------银数数据------------------数据为空");
        }
        log.info("信贷清洗规则---------------------------银数数据------------------处理结束");
        log.info("信贷清洗规则---------------------------委外数据------------------处理开始");
        List<CreditResultDTO> yinShuCreditResultDTOS = creditResultDTOMap.get(Constant.YINSHU);
        List<CreditResultDTO> tongLianCreditResultDTOS = creditResultDTOMap.get(Constant.TONGLIAN);
        if (CollectionUtils.isNotEmpty(yinShuCreditResultDTOS) || CollectionUtils.isNotEmpty(tongLianCreditResultDTOS)) {
            outsouring(yinShuCreditResultDTOS, tongLianCreditResultDTOS);
        } else {
            log.info("信贷清洗规则---------------------------委外数据------------------无委外数据");
        }


        log.info("信贷清洗规则---------------------------委外数据------------------处理结束");
        log.info("信贷清洗规则---------------------------数据并案------------------处理开始");
        List<CreditResultDTO> creditResultDTOS = creditResultDTOMap.get("all");
        Map<String, Map<String, List<CreditResultDTO>>> handleMap = null;
        if (CollectionUtils.isNotEmpty(creditResultDTOS)) {
            log.info("信贷清洗规则---------------------------数据并案------------------重新生成规则开始");
            handleMap = getHandleMap(creditResultDTOS);
            log.info("信贷清洗规则---------------------------数据并案------------------重新生成规则结束");
            log.info("信贷清洗规则---------------------------json文件生成------------------人工外呼生成json文件开始");
            //人工外呼文件生成
            peopleFileGeneration(handleMap);
            log.info("信贷清洗规则---------------------------json文件生成------------------人工外呼生成json文件结束");
            log.info("信贷清洗规则---------------------------json文件生成------------------智能外呼生成json文件开始");
            //智能外呼文件生成
            intelligenceFileGeneration(handleMap);
            log.info("信贷清洗规则---------------------------json文件生成------------------智能外呼生成json文件结束");
        } else {
            log.info("信贷清洗规则---------------------------数据并案------------------无数据并案数据");
        }
        log.info("信贷清洗规则---------------------------保存log表------------------开始");
        savaCreditLog(handleMap, creditResultDTOMap);
        creditResultDTOMap.clear();
        log.info("信贷清洗规则---------------------------保存log表------------------结束");
        log.info("信贷清洗规则---------------------------计算佣金开始------------------开始");
        creditOutcompanyCommissionTask.CreditOutcompanyCommissionTask();
        log.info("信贷清洗规则---------------------------计算佣金开始------------------结束");
        log.info("信贷清洗规则---------------------------删除银数新数据------------------开始 ");
        ckCreditCardLoadNewYinshuMapper.delete();
        log.info("信贷清洗规则---------------------------删除银数新数据------------------结束 ");
        log.info("信贷清洗规则---------------------------删除银数旧数据------------------开始 ");
        ckCreditCardLoadOldYinshuMapper.delete();
        log.info("信贷清洗规则---------------------------删除银数旧数据------------------结束 ");
        log.info("信贷清洗规则---------------------------删除通联新数据------------------开始 ");
        ckCreditCardLoadNewTonglianMapper.delete();
        log.info("信贷清洗规则---------------------------删除通联新数据------------------结束 ");
        log.info("信贷清洗规则---------------------------删除通联旧数据------------------开始 ");
        ckCreditCardLoadOldTonglianMapper.delete();
        log.info("信贷清洗规则---------------------------删除通联新数据------------------结束 ");


        log.info("信贷清洗规则---------------------------数据并案------------------处理结束");
        creditUploadFileTask.CreditUploadFileTask();
        log.info("信贷清洗规则---------------------------任务结束");
    }


    /**
     * 重新生成规则
     *
     * @param creditResultDTOS
     * @return
     */
    private Map<String, Map<String, List<CreditResultDTO>>> getHandleMap(List<CreditResultDTO> creditResultDTOS) throws Exception {
        //外层的map
        Map<String, Map<String, List<CreditResultDTO>>> resultMap = new HashMap<>();
        //内层的map
        Map<String, List<CreditResultDTO>> params = new HashMap<>();
        for (CreditResultDTO creditResultDTO : creditResultDTOS) {
            String identificationNumber = creditResultDTO.getIdentificationNumber();
            if (params.get(identificationNumber) == null) {
                List<CreditResultDTO> creditResultDTOList = new ArrayList<>();
                creditResultDTOList.add(creditResultDTO);
                params.put(identificationNumber, creditResultDTOList);
            } else {
                List<CreditResultDTO> creditResultDTOList = params.get(identificationNumber);
                creditResultDTOList.add(creditResultDTO);
                params.put(identificationNumber, creditResultDTOList);
            }
        }
        for (Map.Entry<String, List<CreditResultDTO>> stringListEntry : params.entrySet()) {
            List<CreditResultDTO> value = stringListEntry.getValue();
            Integer b = 1;
            for (CreditResultDTO creditResultDTO : value) {
                Integer collectionType = creditResultDTO.getCollectionType();
                if (b <= collectionType) {
                    b = collectionType;
                }
            }
            for (CreditResultDTO creditResultDTO : value) {
                resultMap = getRulesMap(creditResultDTO, b, resultMap);
            }
        }
        return resultMap;
    }

    /**
     * 生成规则Map
     *
     * @param creditResultDTO
     * @param result
     * @param rulesMap
     * @return
     */
    private Map<String, Map<String, List<CreditResultDTO>>> getRulesMap(CreditResultDTO creditResultDTO,
                                                                        Integer result,
                                                                        Map<String, Map<String, List<CreditResultDTO>>> rulesMap) throws Exception {
        String resultStr = null;
        switch (result) {
            case 1:
                resultStr = "金信通";
                break;
            case 2:
                resultStr = "智能外呼";
                break;
            case 3:
                resultStr = "人工外呼";
                break;
            case 4:
                resultStr = "委外";
                break;
            case 5:
                resultStr = "错误";
                break;
        }
        String identificationNumber = creditResultDTO.getIdentificationNumber();
        if (rulesMap.get(resultStr) == null) {
            List<CreditResultDTO> creditResultDTOS = new ArrayList<>();
            Map<String, List<CreditResultDTO>> peopleIdMap = new HashMap<>();
            creditResultDTOS.add(creditResultDTO);
            peopleIdMap.put(identificationNumber, creditResultDTOS);
            rulesMap.put(resultStr, peopleIdMap);
        } else {
            Map<String, List<CreditResultDTO>> peopleIdMap = rulesMap.get(resultStr);
            if (peopleIdMap.get(identificationNumber) == null) {
                List<CreditResultDTO> creditResultDTOS = new ArrayList<>();
                creditResultDTOS.add(creditResultDTO);
                peopleIdMap.put(identificationNumber, creditResultDTOS);
                rulesMap.put(resultStr, peopleIdMap);
            } else {
                List<CreditResultDTO> creditResultDTOS = peopleIdMap.get(identificationNumber);
                creditResultDTOS.add(creditResultDTO);
                peopleIdMap.put(identificationNumber, creditResultDTOS);
                rulesMap.put(resultStr, peopleIdMap);
            }
        }
        return rulesMap;
    }

    /**
     * 委外案件处理
     *
     * @param yinShuCreditResultDTOS
     * @param tongLianCreditResultDTOS
     */
    private void outsouring(List<CreditResultDTO> yinShuCreditResultDTOS, List<CreditResultDTO> tongLianCreditResultDTOS) throws Exception {
        String likeBatchNumber = dateUtils.getLikeBatchNumber();
        List<String> cardNumbers=ckCreditOutCompanyDataLogMapper.selectByBatchNumber(likeBatchNumber);
        if (CollectionUtils.isEmpty(cardNumbers)) {
            cardNumbers = new ArrayList<>();
        }
        List<String> strings = ckCreditOutCompanyDataMapper.selectByBatchNumber(likeBatchNumber);
        if (CollectionUtils.isNotEmpty(strings)){
            cardNumbers.addAll(strings);
        }
        log.info("信贷清洗规则---------------------------委外数据------------------银数委外开始");
        Map<String, Map<String, List<CkCreditOutCompanyData>>> ckCreditOutCompanyDataMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(yinShuCreditResultDTOS)) {
            Map<String, List<CkCreditOutCompanyData>> levelMap = new HashMap<>();
            List<CkCreditOutCompanyData> yinShuCkCreditOutCompanyDatas = null;
            for (CreditResultDTO yinShuCreditResultDTO : yinShuCreditResultDTOS) {
                String cardNumber = yinShuCreditResultDTO.getCardNumber();
                if (!cardNumbers.contains(cardNumber)) {
                    CkCreditOutCompanyData ckCreditOutCompanyData = new CkCreditOutCompanyData();
                    BeanUtils.copyProperties(yinShuCreditResultDTO, ckCreditOutCompanyData);
                    ckCreditOutCompanyData.setFenInstitution(yinShuCreditResultDTO.getFhCode());
                    ckCreditOutCompanyData.setZhiInstitution(yinShuCreditResultDTO.getAccountOpeningInstitution());
                    ckCreditOutCompanyData.setAllowType(Constant.YINSHU);
                    String numberOfOverduePeriods = ckCreditOutCompanyData.getNumberOfOverduePeriods();
                    Integer integer = Integer.valueOf(numberOfOverduePeriods);
                    if (integer > 6) {
                        numberOfOverduePeriods="其他";
                    }
                    if (levelMap.get(numberOfOverduePeriods) != null) {
                        yinShuCkCreditOutCompanyDatas = levelMap.get(numberOfOverduePeriods);
                    } else {
                        yinShuCkCreditOutCompanyDatas=new ArrayList<>();
                    }
                    yinShuCkCreditOutCompanyDatas.add(ckCreditOutCompanyData);
                    levelMap.put(numberOfOverduePeriods,yinShuCkCreditOutCompanyDatas);
                }
            }
            if (levelMap.size()>0&&levelMap!=null) {
                ckCreditOutCompanyDataMap.put(Constant.YINSHU, levelMap);
            }
        }
        log.info("信贷清洗规则---------------------------委外数据------------------银数委外结束");
        log.info("信贷清洗规则---------------------------委外数据------------------通联委外开始");
        if (CollectionUtils.isNotEmpty(tongLianCreditResultDTOS)) {
            Map<String, List<CkCreditOutCompanyData>> levelMap = new HashMap<>();
            List<CkCreditOutCompanyData> tongLianCkCreditOutCompanyDatas = null;
            for (CreditResultDTO tongLianCreditResultDTO : tongLianCreditResultDTOS) {
                String cardNumber = tongLianCreditResultDTO.getCardNumber();
                if (!cardNumbers.contains(cardNumber)) {
                    CkCreditOutCompanyData ckCreditOutCompanyData = new CkCreditOutCompanyData();
                    BeanUtils.copyProperties(tongLianCreditResultDTO, ckCreditOutCompanyData);
                    ckCreditOutCompanyData.setAllowType(Constant.TONGLIAN);
                    ckCreditOutCompanyData.setFenInstitution(tongLianCreditResultDTO.getFhCode());
                    ckCreditOutCompanyData.setZhiInstitution(tongLianCreditResultDTO.getAccountOpeningInstitution());
                    String numberOfOverduePeriods = ckCreditOutCompanyData.getNumberOfOverduePeriods();
                    Integer integer = Integer.valueOf(numberOfOverduePeriods);
                    if (integer > 6) {
                        numberOfOverduePeriods="其他";
                    }
                    if (levelMap.get(numberOfOverduePeriods) != null) {
                        tongLianCkCreditOutCompanyDatas = levelMap.get(numberOfOverduePeriods);
                    } else {
                        tongLianCkCreditOutCompanyDatas=new ArrayList<>();
                    }
                    tongLianCkCreditOutCompanyDatas.add(ckCreditOutCompanyData);
                    levelMap.put(numberOfOverduePeriods,tongLianCkCreditOutCompanyDatas);
                }

            }
            if (levelMap.size()>0&&levelMap!=null) {
                ckCreditOutCompanyDataMap.put(Constant.TONGLIAN, levelMap);
            }
        }
        log.info("信贷清洗规则---------------------------委外数据------------------通联委外结束");
        log.info("信贷清洗规则---------------------------委外数据------------------调用委外方法结束");
        if (ckCreditOutCompanyDataMap.size() > 0 && ckCreditOutCompanyDataMap != null) {
           ckCreditOutCompanyDataService.allotOutCompanyData(ckCreditOutCompanyDataMap);
        }
        log.info("信贷清洗规则---------------------------委外数据------------------调用委外方法结束");

    }

    /**
     * 清洗银数数据
     *
     * @param ckCreditCardLoadNewYinShus
     * @param ckCreditCardLoadOldYinShus
     * @param ckCreditStopNoticePeoples
     * @param yinShuPeopleIds
     * @param creditResultDTOMap
     * @return
     */
    private Map<String, List<CreditResultDTO>> yinShuClean(List<CkCreditCardLoadNewYinshu> ckCreditCardLoadNewYinShus,
                                                           List<CkCreditCardLoadOldYinshu> ckCreditCardLoadOldYinShus,
                                                           List<CkCreditStopNoticePerson> ckCreditStopNoticePeoples,
                                                           List<String> yinShuPeopleIds,
                                                           Map<String, List<CreditResultDTO>> creditResultDTOMap,
                                                           List<String> cardNumbers,
                                                           Map<String, String> codeMap) throws Exception {

        log.info("信贷清洗规则----------银数数据-----------------清洗开始");
        boolean n = false;
        boolean o = false;
        if (ckCreditCardLoadNewYinShus.size() > 0) {
            n = true;
        }
        if (ckCreditCardLoadOldYinShus.size() > 0) {
            o = true;
        }
        if (n) {
            log.info("信贷清洗规则----------银数数据-----------------新表清洗开始");
            List<CkCreditCardLoadHistory> ckCreditCardLoadHistories = CkCreditCardLoadNewYinShuClean(ckCreditCardLoadNewYinShus,
                    "NewYinShu", codeMap);
            creditResultDTOMap = historyNewDataClean(ckCreditStopNoticePeoples, yinShuPeopleIds, ckCreditCardLoadHistories, "YinShu", creditResultDTOMap, cardNumbers);
            log.info("信贷清洗规则----------银数数据-----------------新表清洗结束");
        }
        if (o) {
            log.info("信贷清洗规则----------银数数据-----------------旧表清洗开始");
            List<CkCreditCardLoadHistory> ckCreditCardLoadHistories = CkCreditCardLoadOldYinShuClean(ckCreditCardLoadOldYinShus,
                    "OldYinShu", codeMap);
            creditResultDTOMap = historyOldDataClean(ckCreditStopNoticePeoples, ckCreditCardLoadHistories, creditResultDTOMap, Constant.YINSHU);
            log.info("信贷清洗规则----------银数数据-----------------旧表清洗结束");
        }
        return creditResultDTOMap;
    }

    /**
     * 清洗通联数据
     *
     * @param ckCreditCardLoadNewTonglians
     * @param ckCreditCardLoadOldTonglians
     * @param ckCreditStopNoticePeoples
     * @param tongLianPeopleIds
     * @param cardNumbers
     * @throws Exception
     */
    private Map<String, List<CreditResultDTO>> tongLianClean(List<CkCreditCardLoadNewTonglian> ckCreditCardLoadNewTonglians,
                                                             List<CkCreditCardLoadOldTonglian> ckCreditCardLoadOldTonglians,
                                                             List<CkCreditStopNoticePerson> ckCreditStopNoticePeoples,
                                                             List<String> tongLianPeopleIds,
                                                             Map<String, List<CreditResultDTO>> creditResultDTOMap,
                                                             List<String> cardNumbers, Map<String, String> codeMap) throws Exception {
        log.info("信贷清洗规则----------通联数据-----------------清洗开始");
        boolean n = false;
        boolean o = false;
        if (ckCreditCardLoadNewTonglians.size() > 0) {
            n = true;
        }
        if (ckCreditCardLoadOldTonglians.size() > 0) {
            o = true;
        }
        if (n) {
            log.info("信贷清洗规则----------通联数据-----------------新表清洗开始");
            List<CkCreditCardLoadHistory> ckCreditCardLoadHistories = CkCreditCardLoadNewTongLianClean(
                    ckCreditCardLoadNewTonglians, "NewTongLian", codeMap);
            creditResultDTOMap = historyNewDataClean(ckCreditStopNoticePeoples, tongLianPeopleIds,
                    ckCreditCardLoadHistories, "TongLian", creditResultDTOMap, cardNumbers);
            log.info("信贷清洗规则----------通联数据-----------------新表清洗结束");
        }
        if (o) {
            log.info("信贷清洗规则----------通联数据-----------------旧表清洗开始");
            List<CkCreditCardLoadHistory> ckCreditCardLoadHistories = CkCreditCardLoadOldTongLianClean(ckCreditCardLoadOldTonglians,
                    "OldTongLian", codeMap);
            creditResultDTOMap = historyOldDataClean(ckCreditStopNoticePeoples, ckCreditCardLoadHistories, creditResultDTOMap, Constant.TONGLIAN);
            log.info("信贷清洗规则----------通联数据-----------------旧表清洗结束");
        }
        return creditResultDTOMap;
    }

    /**
     * 银数旧表清洗规则
     *
     * @param ckCreditCardLoadOldYinShus
     * @param oldYinShu
     * @return
     */
    private List<CkCreditCardLoadHistory> CkCreditCardLoadOldYinShuClean(List<CkCreditCardLoadOldYinshu> ckCreditCardLoadOldYinShus,
                                                                         String oldYinShu, Map<String, String> codeMap) throws Exception {
        log.info("信贷清洗规则----------银数旧数据-----------------数据存入历史表开始");
        Date date = new Date();
        List<CkCreditCardLoadHistory> ckCreditCardLoadHistories = new ArrayList<>();
        for (CkCreditCardLoadOldYinshu ckCreditCardLoadNewYinShu : ckCreditCardLoadOldYinShus) {
            CkCreditCardLoadHistory ckCreditCardLoadHistory = new CkCreditCardLoadHistory();
            BeanUtils.copyProperties(ckCreditCardLoadNewYinShu, ckCreditCardLoadHistory);
            ckCreditCardLoadHistory.setCurrentDate(date);
            ckCreditCardLoadHistory.setBatchNumber(DateUtils.getBatchNumber());
            //分行coder
            String accountOpeningInstitution = ckCreditCardLoadHistory.getAccountOpeningInstitution();
            if (StringUtils.isNotEmpty(accountOpeningInstitution)) {
                String s = codeMap.get(accountOpeningInstitution);
                if (StringUtils.isNotEmpty(s)) {
                    ckCreditCardLoadHistory.setFhCode(s);
                }
            }
            ckCreditCardLoadHistories.add(ckCreditCardLoadHistory);
            ckCreditCardLoadHistory = null;
        }
        int size = ckCreditCardLoadHistories.size();
        if (size > 0) {
            if (size > 30000) {
                int s = size / 30000;
                for (int i = 1; i <= s; i++) {
                    int b = 30000 * i;
                    List<CkCreditCardLoadHistory> ckOrderLoanLoads = new ArrayList<>();
                    if (i == s) {
                        for (int j = 30000 * (i - 1); j < size; j++) {
                            ckOrderLoanLoads.add(ckCreditCardLoadHistories.get(j));
                        }
                    } else if (i == 1) {
                        for (int j = 0; j < b; j++) {
                            ckOrderLoanLoads.add(ckCreditCardLoadHistories.get(j));
                        }
                    } else {
                        for (int j = 30000 * (i - 1); j < b; j++) {
                            ckOrderLoanLoads.add(ckCreditCardLoadHistories.get(j));
                        }
                    }
                    ckCreditCardLoadHistoryMapper.insertForEach(ckOrderLoanLoads);
                    ckOrderLoanLoads.clear();
                }
            } else {
                ckCreditCardLoadHistoryMapper.insertForEach(ckCreditCardLoadHistories);
            }
        } else {
            log.info("信贷清洗规则----------银数旧数据-----------------银数旧数据为空");
        }

        log.info("信贷清洗规则----------银数旧数据-----------------数据存入历史表结束");
        String nowDayStr = dateUtils.getNowDayStr();
        if (!"01".equalsIgnoreCase(nowDayStr)) {
            log.info("信贷清洗规则----------银数旧数据-----------------数据存入Redis开始");
            if (redisService.hasKey("tjcssys@credit" + oldYinShu + "@" + dateUtils.getNowStr())) {
                Object o = redisService.get("tjcssys@credit" + oldYinShu + "@" + dateUtils.getNowStr());
                List<CkCreditCardLoadOldYinshu> ckCreditCardLoadOldYinshus = JSON.parseArray(String.valueOf(o), CkCreditCardLoadOldYinshu.class);
                ckCreditCardLoadOldYinshus.addAll(ckCreditCardLoadOldYinShus);
                redisService.set("tjcssys@credit" + oldYinShu + "@" + dateUtils.getNowStr(), JSON.toJSONString(ckCreditCardLoadOldYinshus));
            } else {
                redisService.set("tjcssys@credit" + oldYinShu + "@" + dateUtils.getNowStr(), JSON.toJSONString(ckCreditCardLoadOldYinShus));
            }
            log.info("信贷清洗规则----------银数旧数据-----------------数据存入Redis结束");
        } else {
            log.info("信贷清洗规则----------银数旧数据-----------------1号旧数据不存入redis");
        }
        ckCreditCardLoadOldYinShus.clear();
        return ckCreditCardLoadHistories;
    }

    /**
     * 银数新表清洗规则
     *
     * @param ckCreditCardLoadNewYinShus
     * @param newYinShu
     * @return
     * @throws Exception
     */
    private List<CkCreditCardLoadHistory> CkCreditCardLoadNewYinShuClean(List<CkCreditCardLoadNewYinshu> ckCreditCardLoadNewYinShus,
                                                                         String newYinShu,
                                                                         Map<String, String> codeMap) throws Exception {
        log.info("信贷清洗规则----------银数新数据-----------------数据存入历史表开始");
        Date date = new Date();
        String batchNumber = dateUtils.getBatchNumber();
        List<CkCreditCardLoadHistory> ckCreditCardLoadHistories = new ArrayList<>();
        for (CkCreditCardLoadNewYinshu ckCreditCardLoadNewYinshu : ckCreditCardLoadNewYinShus) {
            CkCreditCardLoadHistory ckCreditCardLoadHistory = new CkCreditCardLoadHistory();
            BeanUtils.copyProperties(ckCreditCardLoadNewYinshu, ckCreditCardLoadHistory);
            //性别
            String sex = ckCreditCardLoadHistory.getSex();
            String sexStr = baseInformationUtils.getSexStr(sex);
            ckCreditCardLoadHistory.setSex(sexStr);
            //学历
            String educational = ckCreditCardLoadHistory.getEducational();
            String education = baseInformationUtils.getEducation(educational);
            //分行coder
            String accountOpeningInstitution = ckCreditCardLoadHistory.getAccountOpeningInstitution();
            if (StringUtils.isNotEmpty(accountOpeningInstitution)) {
                String s = codeMap.get(accountOpeningInstitution);
                if (StringUtils.isNotEmpty(s)) {
                    ckCreditCardLoadHistory.setFhCode(s);
                }
            }
            ckCreditCardLoadHistory.setEducational(education);
            ckCreditCardLoadHistory.setCurrentDate(date);
            ckCreditCardLoadHistory.setBatchNumber(batchNumber);
            ckCreditCardLoadHistories.add(ckCreditCardLoadHistory);
            ckCreditCardLoadHistory = null;
        }
        int size = ckCreditCardLoadHistories.size();
        if (size > 0) {
            if (size > 30000) {
                int s = size / 30000;
                for (int i = 1; i <= s; i++) {
                    int b = 30000 * i;
                    List<CkCreditCardLoadHistory> ckOrderLoanLoads = new ArrayList<>();
                    if (i == s) {
                        for (int j = 30000 * (i - 1); j < size; j++) {
                            ckOrderLoanLoads.add(ckCreditCardLoadHistories.get(j));
                        }
                    } else if (i == 1) {
                        for (int j = 0; j < b; j++) {
                            ckOrderLoanLoads.add(ckCreditCardLoadHistories.get(j));
                        }
                    } else {
                        for (int j = 30000 * (i - 1); j < b; j++) {
                            ckOrderLoanLoads.add(ckCreditCardLoadHistories.get(j));
                        }
                    }
                    ckCreditCardLoadHistoryMapper.insertForEach(ckOrderLoanLoads);
                    ckOrderLoanLoads.clear();
                }
            } else {
                ckCreditCardLoadHistoryMapper.insertForEach(ckCreditCardLoadHistories);
            }
            log.info("信贷清洗规则----------银数新数据-----------------数据存入历史表结束");
        } else {
            log.info("信贷清洗规则----------银数新数据-----------------存入历史表数据为空");
        }

        log.info("信贷清洗规则----------银数新数据-----------------数据存入Redis开始");
        if (redisService.hasKey("tjcssys@credit" + newYinShu + "@" + dateUtils.getNowStr())) {
            Object o = redisService.get("tjcssys@credit" + newYinShu + "@" + dateUtils.getNowStr());
            List<CkCreditCardLoadNewYinshu> ckCreditCardLoadNewYinshus = JSON.parseArray(String.valueOf(o), CkCreditCardLoadNewYinshu.class);
            ckCreditCardLoadNewYinshus.addAll(ckCreditCardLoadNewYinShus);
            redisService.set("tjcssys@credit" + newYinShu + "@" + dateUtils.getNowStr(), JSON.toJSONString(ckCreditCardLoadNewYinshus));
        } else {
            redisService.set("tjcssys@credit" + newYinShu + "@" + dateUtils.getNowStr(), JSON.toJSONString(ckCreditCardLoadNewYinShus));
        }
        ckCreditCardLoadNewYinShus.clear();
        log.info("信贷清洗规则----------银数新数据-----------------数据存入Redis结束");
        return ckCreditCardLoadHistories;
    }


    /**
     * 旧表历史数据处理
     *
     * @param ckCreditStopNoticePeoples
     * @param ckCreditCardLoadHistories
     * @param creditResultDTOMap
     * @return
     * @throws Exception
     */
    private Map<String, List<CreditResultDTO>> historyOldDataClean(List<CkCreditStopNoticePerson> ckCreditStopNoticePeoples,
                                                                   List<CkCreditCardLoadHistory> ckCreditCardLoadHistories,
                                                                   Map<String, List<CreditResultDTO>> creditResultDTOMap,
                                                                   String type) throws Exception {
        log.info("信贷清洗规则----------旧表数据-----------------回款数据处理开始");
        ckCreditCardLoadHistories = recoverAndWriteOffData(ckCreditStopNoticePeoples, ckCreditCardLoadHistories);
        log.info("信贷清洗规则----------旧表数据-----------------回款数据处理结束");
        log.info("信贷清洗规则----------旧表数据-----------------回款数据出停催和失联表处理开始");
        ckCreditStopNoticePeoples = stopNoticePeoplesRecoverMoney(ckCreditStopNoticePeoples);
        log.info("信贷清洗规则----------旧表数据-----------------回款数据出停催和失联表处理开始");
        log.info("信贷清洗规则----------旧表数据-----------------数据去除停催和失联数据开始");
        ckCreditCardLoadHistories = stopNoticePerson(ckCreditCardLoadHistories, ckCreditStopNoticePeoples);
        log.info("信贷清洗规则----------旧表数据-----------------数据去除停催和失联数据结束");
        log.info("信贷清洗规则----------旧表数据-----------------根据下发时间控制是否走规则开始");
        ckCreditCardLoadHistories = issueTimeRule(ckCreditCardLoadHistories, type);
        log.info("信贷清洗规则----------旧表数据-----------------根据下发时间控制是否走规则结束");
        log.info("信贷清洗规则----------旧表数据-----------------数据走规则引擎清洗数据开始");
        creditResultDTOMap = ruleCleaning(ckCreditCardLoadHistories, creditResultDTOMap, false);
        log.info("信贷清洗规则----------旧表数据-----------------数据走规则引擎清洗数据结束");
        log.info("信贷清洗规则----------旧表数据-----------------更新卡种信息卡(更新下次发送时间)开始");
        updateCardInformation(creditResultDTOMap);
        log.info("信贷清洗规则----------旧表数据-----------------更新卡种信息卡(更新下次发送时间)结束");
        return creditResultDTOMap;
    }

    /**
     * 获取下次所发送时间
     *
     * @param ckCreditCardLoadHistories
     * @param type
     * @return
     */
    private List<CkCreditCardLoadHistory> issueTimeRule(List<CkCreditCardLoadHistory> ckCreditCardLoadHistories, String type) {
        String likeBatchNumber = dateUtils.getLikeBatchNumber();
        String norm = dateUtils.getNowDayStr();
        Map<String, Object> params = new HashMap<>();
        params.put("norm", norm);
        params.put("likeBatchNumber", likeBatchNumber);
        params.put("type", type);
        List<String> cardNumbers = ckCreditAccountInfoMapper.selectByLikeBatchNumberAndAllowTypeAndNorm(params);
        List<CkCreditCardLoadHistory> ckCreditCardLoadHistorieList = null;
        if (CollectionUtils.isEmpty(cardNumbers)) {
            ckCreditCardLoadHistorieList = new ArrayList<>();
        } else {
            ckCreditCardLoadHistorieList = new ArrayList<>();
            for (CkCreditCardLoadHistory ckCreditCardLoadHistory : ckCreditCardLoadHistories) {
                String cardNumber = ckCreditCardLoadHistory.getCardNumber();
                if (cardNumbers.contains(cardNumber)) {
                    ckCreditCardLoadHistorieList.add(ckCreditCardLoadHistory);
                }
            }
        }
        return ckCreditCardLoadHistorieList;
    }

    /**
     * 处理回款信息和已核销数据
     *
     * @param ckCreditStopNoticePeoples
     * @param ckCreditCardLoadHistories
     * @return
     * @throws Exception
     */
    private List<CkCreditCardLoadHistory> recoverAndWriteOffData(List<CkCreditStopNoticePerson> ckCreditStopNoticePeoples,
                                                                 List<CkCreditCardLoadHistory> ckCreditCardLoadHistories) throws Exception {
        //还款类集合
        List<CkCreditRecoverMoney> ckCreditRecoverMonies = new ArrayList<>();
        //还款集合
        List<CkCreditCardLoadHistory> recoverCkCreditCardLoadHistorys = new ArrayList<>();
        //未还款集合
        List<CkCreditCardLoadHistory> noRecoverCkCreditCardLoadHistorys = new ArrayList<>();
        //核销与已合并集合
        List<CkCreditCardLoadHistory> writeOffCkCreditCardLoadHistorys = new ArrayList<>();
        //历史数据分案
        for (CkCreditCardLoadHistory ckCreditCardLoadHistory : ckCreditCardLoadHistories) {
            String state = ckCreditCardLoadHistory.getState();
            String isMerge = ckCreditCardLoadHistory.getIsMerge();

            if ("2".equalsIgnoreCase(state)) {
                String cardNumber = ckCreditCardLoadHistory.getCardNumber();
                //已回款
                recoverCkCreditCardLoadHistorys.add(ckCreditCardLoadHistory);
                writeOffCkCreditCardLoadHistorys.add(ckCreditCardLoadHistory);
            } else if ("1".equalsIgnoreCase(state)) {
                //已核销
                writeOffCkCreditCardLoadHistorys.add(ckCreditCardLoadHistory);
            } else if ("1".equalsIgnoreCase(isMerge)) {
                //已并案
                writeOffCkCreditCardLoadHistorys.add(ckCreditCardLoadHistory);
            } else {
                //正常下发
                noRecoverCkCreditCardLoadHistorys.add(ckCreditCardLoadHistory);
            }

        }
        log.info("信贷清洗规则----------旧表数据-----------------回款数据处理开始");
        recoverData(ckCreditRecoverMonies, recoverCkCreditCardLoadHistorys);
        log.info("信贷清洗规则----------旧表数据-----------------回款数据处理结束");
        log.info("信贷清洗规则----------旧表数据-----------------核销数据处理开始");
        writeOff(writeOffCkCreditCardLoadHistorys);
        log.info("信贷清洗规则----------旧表数据-----------------核销数据处理结束");
        return noRecoverCkCreditCardLoadHistorys;

    }

    /**
     * 已核销数据处理
     *
     * @param writeOffCkCreditCardLoadHistorys
     * @throws Exception
     */
    private void writeOff(List<CkCreditCardLoadHistory> writeOffCkCreditCardLoadHistorys) throws Exception {
        //log表存储已核销数据
        List<CkCreditLog> creditLogs = new ArrayList<>();
        for (CkCreditCardLoadHistory writeOffCkCreditCardLoadHistory : writeOffCkCreditCardLoadHistorys) {
            CkCreditLog ckCreditLog = new CkCreditLog();
            BeanUtils.copyProperties(writeOffCkCreditCardLoadHistory, ckCreditLog);
            String isMerge = writeOffCkCreditCardLoadHistory.getIsMerge();
            if ("1".equalsIgnoreCase(isMerge)) {
                ckCreditLog.setIsMerge(1);
            }
            creditLogs.add(ckCreditLog);
            ckCreditLog = null;
        }
        log.info("信贷清洗规则----------旧表数据-----------------核销数据保存开始");
        int size = creditLogs.size();
        if (size > 0) {
            if (size > 30000) {
                int s = size / 30000;
                for (int i = 1; i <= s; i++) {
                    int b = 30000 * i;
                    List<CkCreditLog> ckOrderLoanLoads = new ArrayList<>();
                    if (i == s) {
                        for (int j = 30000 * (i - 1); j < size; j++) {
                            ckOrderLoanLoads.add(creditLogs.get(j));
                        }
                    } else if (i == 1) {
                        for (int j = 0; j < b; j++) {
                            ckOrderLoanLoads.add(creditLogs.get(j));
                        }
                    } else {
                        for (int j = 30000 * (i - 1); j < b; j++) {
                            ckOrderLoanLoads.add(creditLogs.get(j));
                        }
                    }
                    ckCreditLogMapper.insertForEach(ckOrderLoanLoads);
                    ckOrderLoanLoads.clear();
                }
            } else {
                ckCreditLogMapper.insertForEach(creditLogs);
            }
            log.info("信贷清洗规则----------旧表数据-----------------核销数据保存结束");
        } else {
            log.info("信贷清洗规则----------旧表数据-----------------核销数据为空");
        }
        creditLogs.clear();

    }

    /**
     * 回款信息处理
     *
     * @param ckCreditRecoverMonies
     * @param recoverCkCreditCardLoadHistorys
     * @throws Exception
     */
    private void recoverData(List<CkCreditRecoverMoney> ckCreditRecoverMonies,
                             List<CkCreditCardLoadHistory> recoverCkCreditCardLoadHistorys) throws Exception {

        //存储卡号和还款类之间的关系
        String batchNumber = dateUtils.getBatchNumber();
        for (CkCreditCardLoadHistory recoverCkCreditCardLoadHistory : recoverCkCreditCardLoadHistorys) {
            CkCreditRecoverMoney ckCreditRecoverMoney = new CkCreditRecoverMoney();
            BeanUtils.copyProperties(recoverCkCreditCardLoadHistory, ckCreditRecoverMoney);
            ckCreditRecoverMoney.setBatchNumber(batchNumber);
            ckCreditRecoverMoney.setCardSpecies(recoverCkCreditCardLoadHistory.getCardType());
            ckCreditRecoverMoney.setIsMerge(Integer.valueOf(recoverCkCreditCardLoadHistory.getIsMerge()));
            ckCreditRecoverMoney.setState(Integer.valueOf(recoverCkCreditCardLoadHistory.getState()));
            ckCreditRecoverMonies.add(ckCreditRecoverMoney);
        }
        log.info("信贷清洗规则----------旧表数据-----------------回款数据保存开始");
        int size = ckCreditRecoverMonies.size();
        if (size > 0) {
            if (size > 30000) {
                int s = size / 30000;
                for (int i = 1; i <= s; i++) {
                    int b = 30000 * i;
                    List<CkCreditRecoverMoney> ckOrderLoanLoads = new ArrayList<>();
                    if (i == s) {
                        for (int j = 30000 * (i - 1); j < size; j++) {
                            ckOrderLoanLoads.add(ckCreditRecoverMonies.get(j));
                        }
                    } else if (i == 1) {
                        for (int j = 0; j < b; j++) {
                            ckOrderLoanLoads.add(ckCreditRecoverMonies.get(j));
                        }
                    } else {
                        for (int j = 30000 * (i - 1); j < b; j++) {
                            ckOrderLoanLoads.add(ckCreditRecoverMonies.get(j));
                        }
                    }
                    ckCreditRecoverMoneyMapper.insertForEach(ckOrderLoanLoads);
                    ckOrderLoanLoads.clear();
                }
            } else {
                ckCreditRecoverMoneyMapper.insertForEach(ckCreditRecoverMonies);
            }
            log.info("信贷清洗规则----------旧表数据-----------------回款数据保存结束");
        } else {
            log.info("信贷清洗规则----------旧表数据-----------------回款数据为空");
        }
        ckCreditRecoverMonies.clear();

    }

    /**
     * 回款出停催或停催表
     *
     * @param ckCreditStopNoticePeoples
     * @throws Exception
     */
    private List<CkCreditStopNoticePerson> stopNoticePeoplesRecoverMoney(List<CkCreditStopNoticePerson> ckCreditStopNoticePeoples) throws Exception {
        String likeBatchNumber = dateUtils.getLikeBatchNumber();
        //证件号码集合
        Set<String> identificationNumbers = new HashSet<>();
        //证件号码关联停催
        Map<String, CkCreditStopNoticePerson> identificationNumbersMap = new HashMap<>();
        for (CkCreditStopNoticePerson ckCreditStopNoticePeople : ckCreditStopNoticePeoples) {
            String identificationNumber = ckCreditStopNoticePeople.getIdentificationNumber();
            identificationNumbers.add(identificationNumber);
            identificationNumbersMap.put(identificationNumber, ckCreditStopNoticePeople);
        }
        //根据批次号和证件号码获取卡信息
        if (CollectionUtils.isNotEmpty(identificationNumbers)) {
            //根据批次号获取卡信息
            Map<String, Object> params = new HashMap<>();
            params.put("batchNumber", likeBatchNumber);
            params.put("identificationNumbers", identificationNumbers);
            List<CkCreditAccountInfo> ckCreditAccountInfos = ckCreditAccountInfoMapper.selectByidentificationNumbers(params);
            //卡号集合
            List<String> cardNums = new ArrayList<>();
            Map<String, List<CkCreditAccountInfo>> ckCreditAccountInfoMap = new HashMap<>();
            for (CkCreditAccountInfo ckCreditAccountInfo : ckCreditAccountInfos) {
                String identificationNumber = ckCreditAccountInfo.getIdentificationNumber();
                List<CkCreditAccountInfo> ckCreditAccountInfos1 = null;
                if (ckCreditAccountInfoMap.get(identificationNumber) != null) {
                    ckCreditAccountInfos1 = ckCreditAccountInfoMap.get(identificationNumber);
                } else {
                    ckCreditAccountInfos1 = new ArrayList<>();
                }
                ckCreditAccountInfos1.add(ckCreditAccountInfo);
                ckCreditAccountInfoMap.put(identificationNumber, ckCreditAccountInfos1);
                String cardNumber = ckCreditAccountInfo.getCardNumber();
                cardNums.add(cardNumber);
                ckCreditAccountInfos1.clear();
            }

            if (CollectionUtils.isNotEmpty(cardNums)) {
                //根据批次号获取还款信息
                List<String>  ckCreditRecoverMoniesCardNums = ckCreditRecoverMoneyMapper.selectByidentificationNumbers(likeBatchNumber, cardNums);
                //已回款的失联或者停催表
                List<CkCreditStopNoticePerson> ckCreditStopNoticePeopleList = new ArrayList<>();
                //遍历卡号Map
                for (Map.Entry<String, List<CkCreditAccountInfo>> stringListEntry : ckCreditAccountInfoMap.entrySet()) {
                    String identificationNumber = stringListEntry.getKey();
                    List<CkCreditAccountInfo> value = stringListEntry.getValue();
                    Integer i = 0;
                    for (CkCreditAccountInfo ckCreditAccountInfo : value) {
                        String cardNumber = ckCreditAccountInfo.getCardNumber();
                        if (!ckCreditRecoverMoniesCardNums.contains(cardNumber)) {
                            i++;
                        }
                    }
                    if (i == 0) {
                        CkCreditStopNoticePerson ckCreditStopNoticePerson = identificationNumbersMap.get(identificationNumber);
                        ckCreditStopNoticePerson.setStatus(3);
                        ckCreditStopNoticePeopleList.add(ckCreditStopNoticePerson);
                        identificationNumbersMap.remove(identificationNumber);
                    }
                    value.clear();
                }
                if (CollectionUtils.isNotEmpty(ckCreditStopNoticePeopleList)) {
                    log.info("信贷清洗规则----------旧表数据-----------------回款数据出停催和失联表保存开始");
                    ckCreditStopNoticePersonMapper.updateForEach(ckCreditStopNoticePeopleList);
                    log.info("信贷清洗规则----------旧表数据-----------------回款数据出停催和失联表保存结束");
                }
                log.info("信贷清洗规则----------旧表数据-----------------剩余停催表处理开始");
                ckCreditStopNoticePeoples = new ArrayList<>();
                for (Map.Entry<String, CkCreditStopNoticePerson> stringCkCreditStopNoticePersonEntry : identificationNumbersMap.entrySet()) {
                    CkCreditStopNoticePerson value = stringCkCreditStopNoticePersonEntry.getValue();
                    ckCreditStopNoticePeoples.add(value);
                }
                ckCreditAccountInfos.clear();
                ckCreditAccountInfoMap.clear();
                cardNums.clear();
                ckCreditRecoverMoniesCardNums.clear();
                ckCreditStopNoticePeopleList.clear();
                log.info("信贷清洗规则----------旧表数据-----------------剩余停催表处理结束");
            } else {
                log.info("信贷清洗规则----------数据为空-----------------数据为空");
            }
        }
        identificationNumbersMap.clear();
        identificationNumbers.clear();
        return ckCreditStopNoticePeoples;
    }

    /**
     * 通联旧表清洗规则
     *
     * @param ckCreditCardLoadOldTonglians
     * @param creditName
     * @return
     * @throws Exception
     */
    private List<CkCreditCardLoadHistory> CkCreditCardLoadOldTongLianClean(List<CkCreditCardLoadOldTonglian> ckCreditCardLoadOldTonglians,
                                                                           String creditName, Map<String, String> codeMap) throws Exception {

        log.info("信贷清洗规则----------通联旧数据-----------------数据存入历史表开始");
        Date date = new Date();
        List<CkCreditCardLoadHistory> ckCreditCardLoadHistories = new ArrayList<>();
        for (CkCreditCardLoadOldTonglian ckCreditCardLoadOldTonglian : ckCreditCardLoadOldTonglians) {
            CkCreditCardLoadHistory ckCreditCardLoadHistory = new CkCreditCardLoadHistory();
            BeanUtils.copyProperties(ckCreditCardLoadOldTonglian, ckCreditCardLoadHistory);
            ckCreditCardLoadHistory.setCurrentDate(date);
            ckCreditCardLoadHistory.setBatchNumber(DateUtils.getBatchNumber());
            //分行coder
            String accountOpeningInstitution = ckCreditCardLoadHistory.getAccountOpeningInstitution();
            if (StringUtils.isNotEmpty(accountOpeningInstitution)) {
                String s = codeMap.get(accountOpeningInstitution);
                if (StringUtils.isNotEmpty(s)) {
                    ckCreditCardLoadHistory.setFhCode(s);
                }
            }
            ckCreditCardLoadHistories.add(ckCreditCardLoadHistory);
            ckCreditCardLoadHistory = null;
        }
        int size = ckCreditCardLoadHistories.size();
        if (size > 0) {
            if (size > 30000) {
                int s = size / 30000;
                for (int i = 1; i <= s; i++) {
                    int b = 30000 * i;
                    List<CkCreditCardLoadHistory> ckOrderLoanLoads = new ArrayList<>();
                    if (i == s) {
                        for (int j = 30000 * (i - 1); j < size; j++) {
                            ckOrderLoanLoads.add(ckCreditCardLoadHistories.get(j));
                        }
                    } else if (i == 1) {
                        for (int j = 0; j < b; j++) {
                            ckOrderLoanLoads.add(ckCreditCardLoadHistories.get(j));
                        }
                    } else {
                        for (int j = 30000 * (i - 1); j < b; j++) {
                            ckOrderLoanLoads.add(ckCreditCardLoadHistories.get(j));
                        }
                    }
                    ckCreditCardLoadHistoryMapper.insertForEach(ckOrderLoanLoads);
                    ckOrderLoanLoads.clear();
                }
            } else {
                ckCreditCardLoadHistoryMapper.insertForEach(ckCreditCardLoadHistories);
            }
            log.info("信贷清洗规则----------通联旧数据-----------------数据存入历史表结束");
        } else {
            log.info("信贷清洗规则----------通联旧数据-----------------数据存入历史表数据为空");
        }
        String nowDayStr = dateUtils.getNowDayStr();
        if (!"01".equalsIgnoreCase(nowDayStr)) {
            log.info("信贷清洗规则----------通联旧数据-----------------数据存入Redis开始");
            if (redisService.hasKey("tjcssys@credit" + creditName + "@" + dateUtils.getNowStr())) {
                Object o = redisService.get("tjcssys@credit" + creditName + "@" + dateUtils.getNowStr());
                List<CkCreditCardLoadOldTonglian> ckCreditCardLoadOldTongliansList = JSON.parseArray(String.valueOf(o), CkCreditCardLoadOldTonglian.class);
                ckCreditCardLoadOldTongliansList.addAll(ckCreditCardLoadOldTonglians);
                redisService.set("tjcssys@credit" + creditName + "@" + dateUtils.getNowStr(), JSON.toJSONString(ckCreditCardLoadOldTongliansList));
            } else {
                redisService.set("tjcssys@credit" + creditName + "@" + dateUtils.getNowStr(), JSON.toJSONString(ckCreditCardLoadOldTonglians));
            }
            log.info("信贷清洗规则----------通联旧数据-----------------数据存入Redis结束");
        } else {
            log.info("信贷清洗规则----------通联旧数据-----------------1号旧数据不存入redis");
        }
        ckCreditCardLoadOldTonglians.clear();
        return ckCreditCardLoadHistories;
    }

    /**
     * 通联新表存入历史表
     *
     * @param ckCreditCardLoadNewTonglians
     * @param creditName
     * @return
     * @throws Exception
     */
    private List<CkCreditCardLoadHistory> CkCreditCardLoadNewTongLianClean(List<CkCreditCardLoadNewTonglian> ckCreditCardLoadNewTonglians,
                                                                           String creditName, Map<String, String> codeMap) throws Exception {

        log.info("信贷清洗规则----------通联新数据-----------------数据存入历史表开始");
        Date date = new Date();
        String batchNumber = dateUtils.getBatchNumber();
        List<CkCreditCardLoadHistory> ckCreditCardLoadHistories = new ArrayList<>();
        for (CkCreditCardLoadNewTonglian ckCreditCardLoadNewTonglian : ckCreditCardLoadNewTonglians) {
            CkCreditCardLoadHistory ckCreditCardLoadHistory = new CkCreditCardLoadHistory();
            BeanUtils.copyProperties(ckCreditCardLoadNewTonglian, ckCreditCardLoadHistory);
            //性别
            String sex = ckCreditCardLoadHistory.getSex();
            String sexStr = baseInformationUtils.getSexStr(sex);
            ckCreditCardLoadHistory.setSex(sexStr);
            //学历
            String educational = ckCreditCardLoadHistory.getEducational();
            String education = baseInformationUtils.getEducation(educational);
            //分行coder
            String accountOpeningInstitution = ckCreditCardLoadHistory.getAccountOpeningInstitution();
            if (StringUtils.isNotEmpty(accountOpeningInstitution)) {
                String s = codeMap.get(accountOpeningInstitution);
                if (StringUtils.isNotEmpty(s)) {
                    ckCreditCardLoadHistory.setFhCode(s);
                }
            }
            ckCreditCardLoadHistory.setEducational(education);
            ckCreditCardLoadHistory.setCurrentDate(date);
            ckCreditCardLoadHistory.setBatchNumber(batchNumber);
            ckCreditCardLoadHistories.add(ckCreditCardLoadHistory);
            ckCreditCardLoadHistory = null;
        }
        int size = ckCreditCardLoadHistories.size();
        if (size > 0) {
            if (size > 30000) {
                int s = size / 30000;
                for (int i = 1; i <= s; i++) {
                    int b = 30000 * i;
                    List<CkCreditCardLoadHistory> ckOrderLoanLoads = new ArrayList<>();
                    if (i == s) {
                        for (int j = 30000 * (i - 1); j < size; j++) {
                            ckOrderLoanLoads.add(ckCreditCardLoadHistories.get(j));
                        }
                    } else if (i == 1) {
                        for (int j = 0; j < b; j++) {
                            ckOrderLoanLoads.add(ckCreditCardLoadHistories.get(j));
                        }
                    } else {
                        for (int j = 30000 * (i - 1); j < b; j++) {
                            ckOrderLoanLoads.add(ckCreditCardLoadHistories.get(j));
                        }
                    }
                    ckCreditCardLoadHistoryMapper.insertForEach(ckOrderLoanLoads);
                    ckOrderLoanLoads.clear();
                }
            } else {
                ckCreditCardLoadHistoryMapper.insertForEach(ckCreditCardLoadHistories);
            }
            log.info("信贷清洗规则----------通联新数据-----------------数据存入历史表结束");
        } else {
            log.info("信贷清洗规则----------通联新数据-----------------存入历史表数据为空");
        }

        log.info("信贷清洗规则----------通联新数据-----------------数据存入Redis开始");
        if (redisService.hasKey("tjcssys@credit" + creditName + "@" + dateUtils.getNowStr())) {
            Object o = redisService.get("tjcssys@credit" + creditName + "@" + dateUtils.getNowStr());
            List<CkCreditCardLoadNewTonglian> ckCreditCardLoadNewTongliansList = JSON.parseArray(String.valueOf(o), CkCreditCardLoadNewTonglian.class);
            ckCreditCardLoadNewTongliansList.addAll(ckCreditCardLoadNewTonglians);
            redisService.set("tjcssys@credit" + creditName + "@" + dateUtils.getNowStr(), JSON.toJSONString(ckCreditCardLoadNewTongliansList));
        } else {
            redisService.set("tjcssys@credit" + creditName + "@" + dateUtils.getNowStr(), JSON.toJSONString(ckCreditCardLoadNewTonglians));
        }
        ckCreditCardLoadNewTonglians.clear();
        log.info("信贷清洗规则----------通联新数据-----------------数据存入Redis结束");
        return ckCreditCardLoadHistories;
    }

    /**
     * 新表数据处理
     *
     * @param ckCreditStopNoticePeoples
     * @param tongLianPeopleIds
     * @param ckCreditCardLoadHistories
     * @param batchNumber
     * @param creditResultDTOMap
     * @return
     * @throws Exception
     */
    private Map<String, List<CreditResultDTO>> historyNewDataClean(List<CkCreditStopNoticePerson> ckCreditStopNoticePeoples,
                                                                   List<String> tongLianPeopleIds,
                                                                   List<CkCreditCardLoadHistory> ckCreditCardLoadHistories,
                                                                   String batchNumber,
                                                                   Map<String, List<CreditResultDTO>> creditResultDTOMap,
                                                                   List<String> cardNumbers) throws Exception {
        log.info("信贷清洗规则----------新表数据-----------------数据存入人员信息表及卡种信息表开始");
        savePeopleInfomationAndAccountInfo(ckCreditCardLoadHistories, tongLianPeopleIds, batchNumber, cardNumbers);
        log.info("信贷清洗规则----------新表数据-----------------数据存入人员信息表及卡种信息表结束");
        log.info("信贷清洗规则----------新表数据-----------------数据去除停催和失联数据开始");
        ckCreditCardLoadHistories = stopNoticePerson(ckCreditCardLoadHistories, ckCreditStopNoticePeoples);
        log.info("信贷清洗规则----------新表数据-----------------数据去除停催和失联数据结束");
        log.info("信贷清洗规则----------新表数据-----------------数据走规则引擎清洗数据开始");
        creditResultDTOMap = ruleCleaning(ckCreditCardLoadHistories, creditResultDTOMap, true);
        log.info("信贷清洗规则----------新表数据-----------------数据走规则引擎清洗数据结束");
        log.info("信贷清洗规则----------新表数据-----------------更新卡种信息卡(更新下次发送时间)开始");
        updateCardInformation(creditResultDTOMap);
        log.info("信贷清洗规则----------新表数据-----------------更新卡种信息卡(更新下次发送时间)结束");
        return creditResultDTOMap;
    }

    /**
     * 更新卡信息表
     *
     * @param creditResultDTOMap
     */
    private void updateCardInformation(Map<String, List<CreditResultDTO>> creditResultDTOMap) {
        List<CkCreditAccountInfo> ckCreditAccountInfos = new ArrayList<>();
        List<CreditResultDTO> all = creditResultDTOMap.get("all");
        if (CollectionUtils.isNotEmpty(all)) {
            for (CreditResultDTO creditResultDTO : all) {
                CkCreditAccountInfo ckCreditAccountInfo = new CkCreditAccountInfo();
                String cardNumber = creditResultDTO.getCardNumber();
                ckCreditAccountInfo.setCardNumber(cardNumber);
                String norm = creditResultDTO.getNorm();
                ckCreditAccountInfo.setNorm(norm);
                ckCreditAccountInfos.add(ckCreditAccountInfo);
            }
            if (CollectionUtils.isNotEmpty(ckCreditAccountInfos)) {
                ckCreditAccountInfoMapper.updateByCardNumberForEach(ckCreditAccountInfos);
            }
        }
    }

    /**
     * 保存log表
     *
     * @param creditResultDTOMap
     * @throws Exception
     */
    private void savaCreditLog(Map<String, Map<String, List<CreditResultDTO>>> handleMap,
                               Map<String, List<CreditResultDTO>> creditResultDTOMap) throws Exception {
        log.info("信贷清洗规则---------------------------委外数据------------------保存log表开始");
        List<CkCreditLog> ckCreditLogs = new ArrayList<>();
        List<CreditResultDTO> creditResultDTOS = new ArrayList<>();
        List<CreditResultDTO> tongLianCreditResultDTOS = creditResultDTOMap.get(Constant.TONGLIAN);
        List<CreditResultDTO> yinShuCreditResultDTOS = creditResultDTOMap.get(Constant.YINSHU);
        if (CollectionUtils.isNotEmpty(tongLianCreditResultDTOS)) {
            creditResultDTOS.addAll(tongLianCreditResultDTOS);
        }
        if (CollectionUtils.isNotEmpty(yinShuCreditResultDTOS)) {
            creditResultDTOS.addAll(yinShuCreditResultDTOS);
        }
        if (CollectionUtils.isNotEmpty(creditResultDTOS)) {
            for (CreditResultDTO creditResultDTO : creditResultDTOS) {
                CkCreditLog ckCreditLog = new CkCreditLog();
                BeanUtils.copyProperties(creditResultDTO, ckCreditLog);
                ckCreditLog.setCollectionTime(new Date());
                ckCreditLog.setIsMerge(Integer.valueOf(creditResultDTO.getIsMerge()));
                ckCreditLog.setCardSpecies(creditResultDTO.getCardType());
                ckCreditLog.setState(Integer.valueOf(creditResultDTO.getState()));
                ckCreditLogs.add(ckCreditLog);
                ckCreditLog = null;
            }
        }
        log.info("信贷清洗规则---------------------------委外数据------------------保存log表结束");
        log.info("信贷清洗规则---------------------------委内数据------------------保存log表开始");
        if (handleMap != null && handleMap.size() > 0) {
            for (Map.Entry<String, Map<String, List<CreditResultDTO>>> stringMapEntry : handleMap.entrySet()) {
                String key = stringMapEntry.getKey();
                Integer outbound = 0;
                if ("金信通".equalsIgnoreCase(key)) {
                    outbound = 1;
                } else if ("智能外呼".equalsIgnoreCase(key)) {
                    outbound = 2;
                } else if ("人工外呼".equalsIgnoreCase(key)) {
                    outbound = 3;
                }
                Map<String, List<CreditResultDTO>> value = stringMapEntry.getValue();
                List<CkCreditLog> ckCreditLogList = new ArrayList<>();
                for (Map.Entry<String, List<CreditResultDTO>> stringListEntry : value.entrySet()) {
                    List<CreditResultDTO> value1 = stringListEntry.getValue();
                    for (CreditResultDTO creditResultDTO : value1) {
                        CkCreditLog ckCreditLog = new CkCreditLog();
                        BeanUtils.copyProperties(creditResultDTO, ckCreditLog);
                        ckCreditLog.setCollectionTime(new Date());
                        ckCreditLog.setCollectionType(outbound);
                        ckCreditLog.setIsMerge(Integer.valueOf(creditResultDTO.getIsMerge()));
                        ckCreditLog.setCardSpecies(creditResultDTO.getCardType());
                        ckCreditLog.setState(Integer.valueOf(creditResultDTO.getState()));
                        ckCreditLogList.add(ckCreditLog);
                    }
                }
                ckCreditLogs.addAll(ckCreditLogList);
                ckCreditLogList.clear();
            }
        }
        log.info("信贷清洗规则---------------------------委内数据------------------保存log表结束");
        log.info("信贷清洗规则---------------------------委内委外数据------------------保存数据库开始");

        int size = ckCreditLogs.size();
        if (size > 0) {
            if (size > 30000) {
                int s = size / 30000;
                for (int i = 1; i <= s; i++) {
                    int b = 30000 * i;
                    List<CkCreditLog> ckOrderLoanLoads = new ArrayList<>();
                    if (i == s) {
                        for (int j = 30000 * (i - 1); j < size; j++) {
                            ckOrderLoanLoads.add(ckCreditLogs.get(j));
                        }
                    } else if (i == 1) {
                        for (int j = 0; j < b; j++) {
                            ckOrderLoanLoads.add(ckCreditLogs.get(j));
                        }
                    } else {
                        for (int j = 30000 * (i - 1); j < b; j++) {
                            ckOrderLoanLoads.add(ckCreditLogs.get(j));
                        }
                    }
                    ckCreditLogMapper.insertForEach(ckOrderLoanLoads);
                    ckOrderLoanLoads.clear();
                }
            } else {
                ckCreditLogMapper.insertForEach(ckCreditLogs);
            }
        } else {
            log.info("信贷清洗规则---------------------------委内委外数据------------------为空");
        }

        ckCreditLogs.clear();
        log.info("信贷清洗规则---------------------------委内委外数据------------------保存数据库开始");
    }

    /**
     * 逐条走规则引擎
     *
     * @param ckCreditCardLoadHistories
     * @param isNew
     * @return
     * @throws Exception
     */
    private Map<String, List<CreditResultDTO>> ruleCleaning(List<CkCreditCardLoadHistory> ckCreditCardLoadHistories,
                                                            Map<String, List<CreditResultDTO>> creditResultDTOMap, boolean isNew) throws Exception {
        for (CkCreditCardLoadHistory ckCreditCardLoadHistory : ckCreditCardLoadHistories) {
            Map<String, String> postParam = getPostParam(ckCreditCardLoadHistory);
            log.info("信贷清洗规则---------------------------规则请求参数为" + JSON.toJSONString(postParam));
            //规则的返回值
            CreditResultDTO creditResultDTO = new CreditResultDTO();
            BeanUtils.copyProperties(ckCreditCardLoadHistory, creditResultDTO);
            Map<String, String> rulesMap = HttpClientUtils.getCreditPostRules(scanningCleaningConfig.getRulesPath(), postParam);
            log.info("信贷清洗规则---------------------------规则返回结果为" + JSON.toJSONString(rulesMap));
            creditResultDTOMap = getCreditResult(creditResultDTOMap, rulesMap, creditResultDTO, isNew);
        }
        ckCreditCardLoadHistories.clear();
        return creditResultDTOMap;
    }

    /**
     * 请求规则后,处理数据
     *
     * @param creditResultDTOMap
     * @param rulesMap
     * @param creditResultDTO
     * @param isNew
     * @return
     * @throws Exception
     */
    private Map<String, List<CreditResultDTO>> getCreditResult(Map<String, List<CreditResultDTO>> creditResultDTOMap,
                                                               Map<String, String> rulesMap, CreditResultDTO creditResultDTO, boolean isNew) throws Exception {
        String outbound = rulesMap.get("outbound");
        if ("4".equalsIgnoreCase(outbound)) {
            if (isNew) {
                String cardType = creditResultDTO.getCardType();
                creditResultDTO.setCollectionType(Integer.valueOf(outbound));
                if ("1".equalsIgnoreCase(cardType)) {
                    List<CreditResultDTO> creditResultDTOS = null;
                    if (CollectionUtils.isEmpty(creditResultDTOMap.get(Constant.TONGLIAN))) {
                        creditResultDTOS = new ArrayList<>();
                    } else {
                        creditResultDTOS = creditResultDTOMap.get(Constant.TONGLIAN);
                    }
                    creditResultDTOS.add(creditResultDTO);
                    creditResultDTOMap.put(Constant.TONGLIAN, creditResultDTOS);
                } else if ("2".equalsIgnoreCase(cardType)) {
                    List<CreditResultDTO> creditResultDTOS = null;
                    if (CollectionUtils.isEmpty(creditResultDTOMap.get(Constant.YINSHU))) {
                        creditResultDTOS = new ArrayList<>();
                    } else {
                        creditResultDTOS = creditResultDTOMap.get(Constant.YINSHU);
                    }
                    creditResultDTOS.add(creditResultDTO);
                    creditResultDTOMap.put(Constant.YINSHU, creditResultDTOS);
                }
            }
            return creditResultDTOMap;
        } else if ("0".equalsIgnoreCase(outbound)) {
            return creditResultDTOMap;
        } else {
            String numberOfOverduePeriods = creditResultDTO.getNumberOfOverduePeriods();
            creditResultDTO.setOverdueLevel("M" + numberOfOverduePeriods);
            creditResultDTO.setCollectionType(Integer.valueOf(outbound));
            //风险等级
            String riskLevel = rulesMap.get("riskLevel");
            creditResultDTO.setRiskLevel(riskLevel);
            //下次下发时间
            String norm = rulesMap.get("norm");
            creditResultDTO.setNorm(norm);
            List<CreditResultDTO> creditResultDTOS = null;
            if (CollectionUtils.isEmpty(creditResultDTOMap.get("all"))) {
                creditResultDTOS = new ArrayList<>();
            } else {
                creditResultDTOS = creditResultDTOMap.get("all");
            }
            creditResultDTOS.add(creditResultDTO);
            creditResultDTOMap.put("all", creditResultDTOS);
            return creditResultDTOMap;
        }
    }

    /**
     * 设置规则参数
     *
     * @param ckCreditCardLoadHistory
     * @return
     */
    private Map<String, String> getPostParam(CkCreditCardLoadHistory ckCreditCardLoadHistory) throws Exception {

        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd");
        String format = simpleDateFormat.format(date);
        Integer day = null;
        //获取redis中的当前时间 如若获取不到应用当前时间
        if (redisService.hasKey("day")) {
            day = Integer.valueOf(String.valueOf(redisService.get("day")));
        } else {
            day = Integer.valueOf(format);
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("projectCode", "rule_cord");
        paramMap.put("enterPoint", scanningCleaningConfig.getCreditEnterPoint());
        Map<String, Object> nCkOrderLoanLoadMap = new HashMap<>();
        Map<String, Object> paramsMap = new HashMap<>();
        String cardType = ckCreditCardLoadHistory.getCardType();
        String numberOfOverduePeriods = ckCreditCardLoadHistory.getNumberOfOverduePeriods();
        Integer collectionScore = ckCreditCardLoadHistory.getCollectionScore();
        String billDay = ckCreditCardLoadHistory.getBillDay();
        paramsMap.put("cardType", cardType);
        paramsMap.put("day", day);
        paramsMap.put("overduePeriods", Integer.valueOf(numberOfOverduePeriods));
        paramsMap.put("billDay", Integer.valueOf(billDay));
        paramsMap.put("score", collectionScore);
        nCkOrderLoanLoadMap.put("resful", paramsMap);
        paramMap.put("businessInput", nCkOrderLoanLoadMap);
        String paramJson = JSON.toJSONString(paramMap);
        Map<String, String> map = JSONUtils.jsonToMap(paramJson);
        return map;
    }

    /**
     * 存入人员信息表和卡信息表
     *
     * @param ckCreditCardLoadHistories
     * @param tongLianPeopleIds
     * @param batchNumber
     * @throws Exception
     */
    private void savePeopleInfomationAndAccountInfo(List<CkCreditCardLoadHistory> ckCreditCardLoadHistories,
                                                    List<String> tongLianPeopleIds, String batchNumber,
                                                    List<String> cardNumbers) throws Exception {
        String likeBatchNumber = dateUtils.getBatchNumber();
        //个人信息Map
        Map<String, CkCreditPeopleInfomation> ckCreditPeopleInfomationMap = new HashMap<>();
        //卡信息Map
        Map<String, CkCreditAccountInfo> ckCreditAccountInfoMap = new HashMap<>();
        for (CkCreditCardLoadHistory ckCreditCardLoadHistory : ckCreditCardLoadHistories) {
            //个人信息
            String identificationNumber = ckCreditCardLoadHistory.getIdentificationNumber();
            if (!tongLianPeopleIds.contains(identificationNumber)) {
                CkCreditPeopleInfomation ckCreditPeopleInfomation = new CkCreditPeopleInfomation();
                BeanUtils.copyProperties(ckCreditCardLoadHistory, ckCreditPeopleInfomation);
                if ("TongLian".equalsIgnoreCase(batchNumber)) {
                    ckCreditPeopleInfomation.setAllowType("1");
                } else if ("YinShu".equalsIgnoreCase(batchNumber)) {
                    ckCreditPeopleInfomation.setAllowType("2");
                }
                ckCreditPeopleInfomation.setBatchNumber(likeBatchNumber);
                ckCreditPeopleInfomationMap.put(identificationNumber, ckCreditPeopleInfomation);
            }
            //卡信息
            String cardNumber = ckCreditCardLoadHistory.getCardNumber();
            if (!cardNumbers.contains(cardNumber)) {
                CkCreditAccountInfo ckCreditAccountInfo = new CkCreditAccountInfo();
                BeanUtils.copyProperties(ckCreditCardLoadHistory, ckCreditAccountInfo);
                ckCreditAccountInfo.setBatchNumber(likeBatchNumber);
                if ("tonglian".equalsIgnoreCase(batchNumber)) {
                    ckCreditAccountInfo.setAllowType("1");
                } else if ("yinshu".equalsIgnoreCase(batchNumber)) {
                    ckCreditAccountInfo.setAllowType("2");
                }
                ckCreditAccountInfoMap.put(cardNumber, ckCreditAccountInfo);
            }
        }
        log.info("信贷清洗规则---------------------------存入数据库人员信息表开始");
        //个人信息集合
        List<CkCreditPeopleInfomation> ckCreditPeopleInfomations = new ArrayList<>();
        //卡信息集合
        List<CkCreditAccountInfo> ckCreditAccountInfos = new ArrayList<>();
        for (Map.Entry<String, CkCreditPeopleInfomation> stringCkCreditPeopleInfomationEntry : ckCreditPeopleInfomationMap.entrySet()) {
            CkCreditPeopleInfomation value = stringCkCreditPeopleInfomationEntry.getValue();
            ckCreditPeopleInfomations.add(value);
        }
        for (Map.Entry<String, CkCreditAccountInfo> stringCkCreditAccountInfoEntry : ckCreditAccountInfoMap.entrySet()) {
            CkCreditAccountInfo value = stringCkCreditAccountInfoEntry.getValue();
            ckCreditAccountInfos.add(value);
        }
        int size = ckCreditPeopleInfomations.size();
        if (size > 0) {
            if (size > 30000) {
                int s = size / 30000;
                for (int i = 1; i <= s; i++) {
                    int b = 30000 * i;
                    List<CkCreditPeopleInfomation> ckOrderLoanLoads = new ArrayList<>();
                    if (i == s) {
                        for (int j = 30000 * (i - 1); j < size; j++) {
                            ckOrderLoanLoads.add(ckCreditPeopleInfomations.get(j));
                        }
                    } else if (i == 1) {
                        for (int j = 0; j < b; j++) {
                            ckOrderLoanLoads.add(ckCreditPeopleInfomations.get(j));
                        }
                    } else {
                        for (int j = 30000 * (i - 1); j < b; j++) {
                            ckOrderLoanLoads.add(ckCreditPeopleInfomations.get(j));
                        }
                    }
                    ckCreditPeopleInfomationMapper.insertForEach(ckOrderLoanLoads);
                    ckOrderLoanLoads.clear();
                }
            } else {
                ckCreditPeopleInfomationMapper.insertForEach(ckCreditPeopleInfomations);
            }
            log.info("信贷清洗规则---------------------------存入数据库人员信息表结束");
        } else {
            log.info("信贷清洗规则---------------------------存入数据库人员信息表为空");
        }

        log.info("信贷清洗规则---------------------------存入数据库卡信息表开始");
        size = ckCreditAccountInfos.size();
        if (size > 0) {
            if (size > 30000) {
                int s = size / 30000;
                for (int i = 1; i <= s; i++) {
                    int b = 30000 * i;
                    List<CkCreditAccountInfo> ckOrderLoanLoads = new ArrayList<>();
                    if (i == s) {
                        for (int j = 30000 * (i - 1); j < size; j++) {
                            ckOrderLoanLoads.add(ckCreditAccountInfos.get(j));
                        }
                    } else if (i == 1) {
                        for (int j = 0; j < b; j++) {
                            ckOrderLoanLoads.add(ckCreditAccountInfos.get(j));
                        }
                    } else {
                        for (int j = 30000 * (i - 1); j < b; j++) {
                            ckOrderLoanLoads.add(ckCreditAccountInfos.get(j));
                        }
                    }
                    ckCreditAccountInfoMapper.insertForEach(ckOrderLoanLoads);
                    ckOrderLoanLoads.clear();
                }
            } else {
                ckCreditAccountInfoMapper.insertForEach(ckCreditAccountInfos);
            }
            ckCreditPeopleInfomations.clear();
            ckCreditAccountInfos.clear();
            log.info("信贷清洗规则---------------------------存入数据库卡信息表结束");
        } else {
            log.info("信贷清洗规则---------------------------存入数据库卡信息表为空");
        }
    }

    /**
     * 排除停催和失联
     *
     * @param ckCreditCardLoadHistories
     * @param ckCreditStopNoticePeoples
     * @return
     * @throws Exception
     */
    private List<CkCreditCardLoadHistory> stopNoticePerson(List<CkCreditCardLoadHistory> ckCreditCardLoadHistories,
                                                           List<CkCreditStopNoticePerson> ckCreditStopNoticePeoples) throws Exception {
        List<CkCreditCardLoadHistory> ckCreditCardLoadHistorieList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(ckCreditStopNoticePeoples)) {
            List<String> peopleIds = new ArrayList<>();
            for (CkCreditStopNoticePerson ckCreditStopNoticePeople : ckCreditStopNoticePeoples) {
                String peopleId = ckCreditStopNoticePeople.getIdentificationNumber();
                peopleIds.add(peopleId);
            }
            for (CkCreditCardLoadHistory ckCreditCardLoadHistory : ckCreditCardLoadHistories) {
                String identificationNumber = ckCreditCardLoadHistory.getIdentificationNumber();
                String cardType = ckCreditCardLoadHistory.getCardType();
                //通联
                if ("1".equalsIgnoreCase(cardType)) {
                    ckCreditCardLoadHistorieList.add(ckCreditCardLoadHistory);
                    continue;
                }
                //银数
                String numberOfOverduePeriods = ckCreditCardLoadHistory.getNumberOfOverduePeriods();
                if (StringUtils.isNotEmpty(numberOfOverduePeriods)) {
                    //期数大于等于2
                    Integer integer = Integer.valueOf(numberOfOverduePeriods);
                    if (integer >= 2) {
                        ckCreditCardLoadHistorieList.add(ckCreditCardLoadHistory);
                        continue;
                    }
                    //委内停催
                    if (!peopleIds.contains(identificationNumber)) {
                        ckCreditCardLoadHistorieList.add(ckCreditCardLoadHistory);
                        continue;
                    }
                }
            }
            ckCreditCardLoadHistories.clear();
           // ckCreditStopNoticePeoples.clear();
        } else {
            ckCreditCardLoadHistorieList = ckCreditCardLoadHistories;
        }

        return ckCreditCardLoadHistorieList;
    }

    /**
     * 人工文件生成
     *
     * @param handleMap
     */
    private void peopleFileGeneration(Map<String, Map<String, List<CreditResultDTO>>> handleMap) throws Exception {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String dateStr = simpleDateFormat.format(date);
        log.info("人工外呼生成文件开始");
        Map<String, Map<String, List<CreditResultDTO>>> peopleMap = new HashMap<>();

        if (handleMap.get("人工外呼") != null) {
            peopleMap.put("人工外呼", handleMap.get("人工外呼"));

            int count = 0;
            for (Map.Entry<String, Map<String, List<CreditResultDTO>>> stringMapEntry : peopleMap.entrySet()) {
                Map<String, List<CreditResultDTO>> value = stringMapEntry.getValue();
                for (Map.Entry<String, List<CreditResultDTO>> stringListEntry : value.entrySet()) {
                    List<CreditResultDTO> value1 = stringListEntry.getValue();
                    count += value1.size();
                }
            }
            JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd";
            String peopleJsonStr = JSON.toJSONString(peopleMap, SerializerFeature.WriteDateUseDateFormat);
            File peopleJsonFile = new File(scanningCleaningConfig.getCreditPeopleUploadJsonPath());
            if (!peopleJsonFile.exists()) {
                peopleJsonFile.mkdirs();
            }
            String peopleJsonPath = scanningCleaningConfig.getCreditPeopleUploadJsonPath() + scanningCleaningConfig.getCreditPrefixUploadJsonPath().replace("yyyyMMdd", dateStr);
            log.info("人工外呼生成json文件开始,文件名称为:" + peopleJsonPath);
            writeJsonFile(peopleJsonPath, peopleJsonStr);
            log.info("人工外呼处理成json格式结束");
            String peopleOkPath = peopleJsonPath.replace("json", "ok");
            log.info("人工外呼生成ok文件开始,文件名称为:" + peopleOkPath);
            writeJsonFile(peopleOkPath, peopleJsonStr);
            log.info("人工外呼处理成ok格式结束");
            log.info("人工外呼存储总条数到redis开始");
            Map<String, Object> redisMap = new HashMap<>();
            redisMap.put("CreditEsbFilePath", scanningCleaningConfig.getPackageName() + "creditPeople/" + scanningCleaningConfig.getCreditPrefixUploadJsonPath().replace("yyyyMMdd", dateStr));
            redisMap.put("CreditEsbCount", count);
            redisService.hmset("CreditEsbFilePathAndCount", redisMap);
            //存储操作log

            log.info("人工外呼存储总条数到redis结束");
            log.info("人工外呼生成文件结束");
        } else {
            log.info("人工外呼数据为空");
        }
    }

    /**
     * 智能外呼文件处理
     *
     * @param handleMap
     * @throws Exception
     */
    private void intelligenceFileGeneration(Map<String, Map<String, List<CreditResultDTO>>> handleMap) throws Exception {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String dateStr = simpleDateFormat.format(date);
        log.info("智能外呼处理文件开始");
        Map<String, List<CreditResultDTO>> intelligenceMap = new HashMap<>();

        if (handleMap.get("智能外呼") != null) {
            Map<String, List<CreditResultDTO>> maps = handleMap.get("智能外呼");
            List<CreditResultDTO> creditResultDTOS = new ArrayList<>();
            for (Map.Entry<String, List<CreditResultDTO>> stringListEntry : maps.entrySet()) {
                List<CreditResultDTO> value = stringListEntry.getValue();
                creditResultDTOS.addAll(value);
            }
            intelligenceMap.put("智能外呼",creditResultDTOS);
            JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd";
            String intelligenceJsonStr = JSON.toJSONString(intelligenceMap, SerializerFeature.WriteDateUseDateFormat);
            File intelligenceJsonFile = new File(scanningCleaningConfig.getCreditIntelligenceUploadJsonPath());
            if (!intelligenceJsonFile.exists()) {
                intelligenceJsonFile.mkdirs();
            }
            String intelligenceJsonPath = scanningCleaningConfig.getCreditIntelligenceUploadJsonPath() + scanningCleaningConfig.getCreditPrefixUploadJsonPath().replace("yyyyMMdd", dateStr);
            log.info("智能外呼生成json文件开始,文件名称为:" + intelligenceJsonPath);
            writeJsonFile(intelligenceJsonPath, intelligenceJsonStr);
            log.info("智能外呼处理成json格式结束");
            //存储操作log
            String intelligenceOkPath = intelligenceJsonPath.replace("json", "ok");
            log.info("智能外呼生成ok文件开始,文件名称为:" + intelligenceJsonPath);
            writeJsonFile(intelligenceOkPath, intelligenceJsonStr);
            log.info("智能外呼处理成ok格式结束");
            log.info("智能外呼处理文件结束");
        } else {
            log.info("智能外呼处理文件为空");
        }

    }

    /**
     * 生成json文件
     *
     * @param filePath
     * @param sets
     * @return
     * @throws Exception
     */
    private boolean writeJsonFile(String filePath, String sets) throws Exception {
        FileWriter fw;
        fw = new FileWriter(filePath);
        PrintWriter out = new PrintWriter(fw);
        try {
            out.write(sets);
            out.println();
            return true;
        } catch (Exception e) {
            throw e;
        } finally {
            fw.close();
            out.close();
        }
    }
}
